import { ElLoading, ElMessage } from "element-plus";
import { defineStore } from "pinia";
import { ref, watch } from "vue";
import UserAPI from "@/api/user";
import { Session } from "@/utils/storage";
import cookie from "js-cookie";
import router from "@/router";
import { useMenuStore } from "@/pinia/menu";
import type { NavigationGuardNext, RouteLocationNormalized, RouteRecordRaw } from "vue-router";

export const useUserStore = defineStore("user", () => {
  /**用户信息 */
  const userInfo = ref({
    nickName: "",
    department: "",
  });

  const GetUserInfo = async () => {
    const res = await UserAPI.getUserInfo();
    if (res.code === 0) {
      setUserInfo(res.data.userInfo);
    }
    return res;
  };

  const setUserInfo = (val) => {
    userInfo.value = val;
  };

  /**鉴权token */
  const token = ref(
    Session.get("token") || ""
  );

  const setToken = (val) => {
    token.value = val;
    Session.set("token", val);
  };

  const loginLoading = ref(null);

  /**用户登录 */
  const Login = async (loginInfo) => {
    loginLoading.value = ElLoading.service({
      fullscreen: true,
      text: "正在登录，请稍候...",
    });

    const res = await UserAPI.login(loginInfo);

    // 登陆失败，直接返回
    if (res.code !== 200) {
      loginLoading.value.close();
      return false;
    }

    // 停顿查看ElLoadin效果
    // waitProgress(3000);

    // 登陆成功，设置用户信息和权限相关信息
    setUserInfo(res.data.user);
    setToken(res.data.token);

    // 全部操作均结束，关闭loading并返回
    loginLoading.value.close();
    return true;
  };

  /* 用户登出*/
  const Logout = async () => {
    const res = await UserAPI.logout();

    // 登出失败
    if (res.code !== 0) {
      return;
    }

    // 清空浏览器缓存
    await ClearStorage();

    // 路由到登录页
    router.push({ name: "Login", replace: true });
    window.location.reload();
  };

  /* 清空浏览器缓存 */
  const ClearStorage = async () => {
    token.value = "";
    sessionStorage.clear();
    window.localStorage.removeItem("token");
    cookie.remove("refresh_token");
  };

  return {
    userInfo,
    token,
    GetUserInfo,
    Login,
    Logout,
    setToken,
    loginLoading,
    ClearStorage,
  };
});
